/**
 * 
 */
package cn.ivicar.app.quartz;

import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.SimChargeRecord;
import cn.com.carsmart.ws.service.SimChargeRecordManager;
import cn.ivicar.app.guice.AppGuiceConfig;
import cn.ivicar.sim.util.SimProperties;

/**
 * @author liurunbin 2017年7月14日 cn.ivicar.app.quartz
 */
public class OrderTask implements Job {

	private SimChargeRecordManager simChargeRecordManager = AppGuiceConfig.getStaticInjector()
			.getInstance(SimChargeRecordManager.class);
	private static transient final Logger LOGGER = LoggerFactory.getLogger(OrderTask.class);

	private static long TIME_OUT = SimProperties.getOrderTimeOut();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	 */
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		BaseExample example = simChargeRecordManager.getExample();
		example.or().andPropertyEqualTo(1, "chargeStatus").andPropertyEqualTo(false, "isDeleted");
		List<SimChargeRecord> list = simChargeRecordManager.listByBaseExample(example);
		if (list == null || list.isEmpty()) {
			LOGGER.info("系统中没有未支付订单");
			return;
		}

		for (SimChargeRecord record : list) {
			if ((System.currentTimeMillis() - record.getCreated().getTime()) > TIME_OUT) {
				record.setIsDeleted(true);
				simChargeRecordManager.update(record);
				LOGGER.info(String.format("订单[chargeId:%s]超过%s ms 未支付，标记为删除", record.getChargeId(), TIME_OUT));
			}
		}

	}

}
